<template>
  <div>
    <!-- 头部 -->
    <nav-bar>
      <template v-slot:default>用户登录</template>
    </nav-bar>

    <!-- 图片 -->
    <div style="margin-top: 45px; margin-bottom: 40px;" >
      <div style="text-align: center; width: 375px; height: 150px;">
        <img src="../../assets/images/bgc.jpg" alt="">
      </div>
    </div>

    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="email"
        name="电子邮箱"
        label="电子邮箱"
        placeholder="电子邮箱"
        :rules="[{ required: true, message: '请填写邮箱' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <div class="link-login" @click="$router.push('/register')">
          没有账号，立即注册
        </div>
        <van-button round block type="primary" native-type="submit">登录</van-button>
      </div>
    </van-form>


  </div>
</template>

<script>
import NavBar from 'components/common/navbar/NavBar.vue';
import { login } from 'network/user.js'
import {useRouter} from 'vue-router'
import {useStore} from 'vuex'
import { reactive, toRefs } from 'vue';
import { Notify, Toast } from 'vant';
export default {
  name: 'Login',
  setup () {
    const router = useRouter()
    const store = useStore()

    // 用户注册填写的信息
    const userInfo = reactive({
      password: '123456',
      email: 'zhu123@qq.com'
    })

    // 提交事件
    const onSubmit = async () => {
      const data = await login(userInfo)
      // 登录失败的情况
      if(!data.token_type) return 

      // 登录成功的情况
      // 1. 将 token 保存在本地
      window.localStorage.setItem('token', data.access_token)

      // 2. 在 vuex 临时存储是否登录 isLogin
      store.commit('setIsLogin', true)
      // 3. 成功的提示
      Toast.success('登录成功！')
      store.dispatch('updateCart')

      
      // 1 秒后返回上一个页面
      setTimeout(()=>{
        router.go(-1)
      }, 1000)

      userInfo.email = ''
      userInfo.password = ''

    }

    return {
      ...toRefs(userInfo),
      onSubmit
    };
  },

  components: {
    NavBar,
  }
}

</script>
<style lang='scss' scoped>
.link-login {
  width: 37%;
  font-size: 14px;
  margin-bottom: 20px;
  // color: #42b983;
  color: gray;
  text-align-last: left;
}
</style>